/******************************************************************************
 * @File name   :      MaintainMasterDataController.java
 *
 * @Author      :      ANMA
 *
 * @Date        :      Jul 15, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * ----------------------------------------------------------------------------
 * Date                         Who         Version         Comments
 * Jul 15, 2015 11:38:08 AM    ANMA      1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.purchase.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.crmdp.dealer.activation.dto.ActivationResultsDto;
import com.cap.bts.crmdp.dealer.mars.service.IMarsMemberPackageService;
import com.cap.bts.crmdp.dealer.member.constants.MaintainMemberConstants;
import com.cap.bts.crmdp.dealer.member.domain.CarPlateInfo;
import com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto;
import com.cap.bts.crmdp.dealer.member.dto.MemberResultsDto;
import com.cap.bts.crmdp.dealer.member.service.IMaintainCarPlateService;
import com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService;
import com.cap.bts.crmdp.dealer.packagegift.service.IMemberGiftService;
import com.cap.bts.crmdp.dealer.purchase.constants.PurchaseConstants;
import com.cap.bts.crmdp.dealer.purchase.domain.CardInventory;
import com.cap.bts.crmdp.dealer.purchase.dto.MemberPackageInfoSubmitDto;
import com.cap.bts.crmdp.dealer.purchase.service.ICardInventoryService;
import com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService;
import com.cap.bts.crmdp.dealer.purchase.service.IPackageDefinitionService;
import com.cap.bts.crmdp.dealer.purchase.service.IPurchasePackageService;
import com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.exception.AppException;

/**
 * 会员流程-购买
 */
@Controller
@RequestMapping(value = "/crmdp/dealer/purchase")
public class PurchaseController extends BaseController {
   
    private static final Logger LOGGER            = Logger.getLogger(PurchaseController.class);

    @Autowired
    IPackageDefinitionService packageDefinitionService;

    @Autowired
    ICardInventoryService cardInventoryService;

    @Autowired
    IPurchasePackageService purchasePackageService;

    @Autowired
    IMemberPackageService memberPackageService;
    
    @Autowired
    IMarsMemberPackageService marsMemberPackageService;

    @Autowired
    IRedemptionService redemptionService;

    @Autowired
    IMaintainCarPlateService maintainCarPlateService;

    @Autowired
    IMaintainMemberService maintainMemberService;

    @Autowired
    private ICodeMapping codeMapping;
    
    @Autowired
    IMemberGiftService memberGiftService;
    
    @RequestMapping(value = "/toMemberPurchase")
    public String toMemberPurchase(MemberResultsDto dto, Model model, HttpServletRequest request)
        throws AppException {
        try {
            dto.setCarPlate(java.net.URLDecoder.decode(dto.getCarPlate(),
                PurchaseConstants.ENCODE_UTF_8));
            dto.setMemberName(java.net.URLDecoder.decode(dto.getMemberName(),
                PurchaseConstants.ENCODE_UTF_8));
        } catch (UnsupportedEncodingException e) {
            throw new AppException("toMemberPurchase", e);
        }
        model.addAttribute("packageDefinitionListDto",
            packageDefinitionService.getAllPackageDefinitionList());
        model.addAttribute(PurchaseConstants.MEMBER_RESULTS_DTO, dto);
        model.addAttribute(PurchaseConstants.IS_MEMBER, true);
        MemberQueryDto memberQueryDto = (MemberQueryDto) request.getSession().getAttribute(
            "getMaintainMemberPage");
        memberQueryDto.setIsSelected("radio" + dto.getId() + dto.getCarPlate() + "Rad");
        return "/purchase/purchase";
    }
    
    @RequestMapping(value = "/toUpdateMemberPage")
    public String toUpdateMemberPage(MemberResultsDto dto, Model model, HttpServletRequest request)
        throws AppException {
        try {
            dto.setMemberName(java.net.URLDecoder.decode(dto.getMemberName(),
                PurchaseConstants.ENCODE_UTF_8));
            dto.setMobilePhone(java.net.URLDecoder.decode(dto.getMobilePhone(),
                PurchaseConstants.ENCODE_UTF_8));
            dto.setCarPlate(java.net.URLDecoder.decode(dto.getCarPlate(),
                PurchaseConstants.ENCODE_UTF_8));
        } catch (UnsupportedEncodingException e) {
            throw new AppException("toMemberPurchase", e);
        }
        MemberQueryDto memberQueryDto = new MemberQueryDto();
        memberQueryDto.setDealerId(UserUtil.getCurrentUser().getDealerId());
        memberQueryDto.setMobilePhone(dto.getMobilePhone());
        List<MemberResultsDto> list = maintainMemberService
            .getMemberByMobilePhoneOrMemberId(memberQueryDto);
        if (list != null && !list.isEmpty()) {
            Long memberId = list.get(0).getId();
            String memberName = list.get(0).getMemberName();
            dto.setMemberName(memberName);
            List<CarPlateInfo> carPlateInfo = maintainCarPlateService
                .getCarPlateInfoListByCarPlateOrMemberId(null, memberId);
            Long dealerId = UserUtil.getCurrentUser().getDealerId();
            List<CarPlateInfo> carPlateWithPackage = new ArrayList<CarPlateInfo>();
            List<CarPlateInfo> carPlateWithoutPackage = new ArrayList<CarPlateInfo>();
            for (int i = 0; i < carPlateInfo.size(); i++) {
                CarPlateInfo plate = maintainCarPlateService.getCarPlateListWithPackage(dealerId, 
                    carPlateInfo.get(i).getId(), memberId);
                if(plate != null){
                    carPlateWithPackage.add(plate);
                }else{
                    carPlateWithoutPackage.add(carPlateInfo.get(i));
                }
            }
            model.addAttribute("carPlateInfoWithoutPackage", carPlateWithoutPackage);
            model.addAttribute("carPlateWithPackage", carPlateWithPackage);
        }
        CodeInfo codeInfo = codeMapping.getCodeInfoByCode(MaintainMemberConstants.UPDATE_TIMES);
        if(codeInfo != null){
            dto.setUpdateCarplateTimes(Integer.parseInt(codeInfo.getValue()));
        }
        model.addAttribute(PurchaseConstants.MEMBER_RESULTS_DTO, dto);
        model.addAttribute(PurchaseConstants.IS_MEMBER, true);
        if (dto.isRedirected()) {
            memberQueryDto = (MemberQueryDto) request.getSession().getAttribute(
                "getMaintainMemberPage");
            memberQueryDto.setIsSelected("radio" + dto.getId() + dto.getCarPlate() + "Rad");
        }
        return "/member/updateMember";
    }

    /**
     * 获取库存信息
     * 
     * @Date : 2015-7-15
     * @param dto
     *            MemberResultsDto
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/getPackageInfo")
    @ResponseBody
    public String getPackageInfo(Long cardDefId, Model model,
        HttpServletRequest request) throws AppException {
        String quantity = "0";
        CardInventory cardInventory = cardInventoryService.getCardInventoryInfo(cardDefId,UserUtil.getCurrentUser().getDealerId());
        if (cardInventory != null) {
            quantity = cardInventory.getOnhandQuantity().toString();
        }
        return quantity;
    }
    

    /**
     * 检查是否存在该实物卡
     * 
     * @Date : 2015-7-15
     * @param dto
     *            MemberResultsDto
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/checkMemberPackageInfoExsit")
    @ResponseBody
    public Boolean checkMemberPackageInfoExsit(MemberPackageInfoSubmitDto dto, Model model,
        HttpServletRequest request) throws AppException {
        return memberPackageService.checkMemberPackageExsit(dto);
    }
    
    
    /**
     * 当前激活
     * 
     * @Date : 2015-7-15
     * @param dto
     *            MemberPackageInfoSubmitDto
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/activeNow")
    @ResponseBody
    public Map<String,Object> activeNow(MemberPackageInfoSubmitDto dto, Model model, HttpServletRequest request)
        throws AppException {
        
        Map<String,Object> rtnMap=new HashMap<String, Object>();
        dto.setDealerId(UserUtil.getCurrentUser().getDealerId());
        rtnMap.put("result", true);
        try {
            purchasePackageService.purchasePackage(dto);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(),e);
            rtnMap.put("result", false);
            rtnMap.put("errorMsg", e.getMessage());
            return rtnMap;
        }
        return rtnMap;
    }

    /**
     * 当前激活
     * 
     * @Date : 2015-7-15
     * @param dto
     *            MemberPackageInfoSubmitDto
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/activeNowPhysical")
     String activeNowPhysical(MemberPackageInfoSubmitDto dto, Model model,
        HttpServletRequest request) throws AppException {
        dto.setDealerId(UserUtil.getCurrentUser().getDealerId());
        ActivationResultsDto activationResultsDto = new ActivationResultsDto();
        activationResultsDto.setMemberId(dto.getMemberId());
        
        activationResultsDto.setPackageName(dto.getPackageName());
       
        activationResultsDto.setPackageNumber(dto.getPackageNumber());
        activationResultsDto.setMobilePhone(dto.getMobilePhone());
        activationResultsDto.setCarPlate(dto.getCarPlate());
        activationResultsDto.setMemberName(dto.getMemberName());
        activationResultsDto.setPackageDefId(dto.getPackageDefId());
        activationResultsDto.setPrice(dto.getPrice());
        activationResultsDto.setOnhandQuantity(dto.getOnhandQuantity());
        activationResultsDto.setFromPurchasePage(dto.getFromPurchasePage());
        model.addAttribute("dto", activationResultsDto);
        return "/activation/activation";
    }

    /**
     * 事后激活
     * 
     * @Date : 2015-7-15
     * @param dto
     *            MemberPackageInfoSubmitDto
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/activeAfter")
    @ResponseBody
    public Map<String, Object> activeAfter(MemberPackageInfoSubmitDto dto, Model model,
        HttpServletRequest request) throws AppException {
        Map<String, Object> resultMap=new HashMap<String, Object>();
        dto.setDealerId(UserUtil.getCurrentUser().getDealerId());
        try {
            purchasePackageService.purchasePackage(dto);
            resultMap.put("result", true);
        } catch (AppException e) {
            resultMap.put("result", false);
            resultMap.put("errorMsg", e.getMessage());
            LOGGER.error("purchasePackage-activeAfter", e);
        }
        return resultMap;
    }

}
